import { Card, Table, Form, Input, Button, Select, DatePicker, Space } from 'antd'
import { useSearchParams } from 'react-router-dom'
import { DebounceSelect } from '@/components/DebounceSelect'
import { http, getMaxLength } from '@/utils'
import React, { useEffect, useRef, useState } from 'react'
import moment from 'moment'
const { RangePicker } = DatePicker

// Usage of DebounceSelect
function fetchUserList (val) {
  return http.post('/alarm/deliversign/findFeatureInfoByPage', {
    userId: 1,
    keyWord: val,
    pageNum: 1,
    pageSize: 20
  }).then(res => {
    return res.body.list.map(item => ({
      label: item.displayName,
      value: item.id,
    }))
  })
}

const Signal = () => {
  const [form] = Form.useForm()
  const [paramsUrl] = useSearchParams()
  // const [expandedRowKeys, setExpandedRowKeys] = useState([])
  const [signalData, setSignalData] = useState({
    list: [],
    count: 100
  })
  const [defaultopt, setDefaultopt] = useState([])
  const [freqListOpt, setFreqListOpt] = useState([])
  const factorListOptRef = useRef([])
  // 默认查询最近15天分值趋势
  const defaultTime = [moment(new Date()).add(-15, 'd'), moment(new Date())]
  const [columns, setColumns] = useState([
    {
      title: '品种名称', width: 100, render: (data) => {
        return (
          <Space size="middle">
            <span>{data.featureName}</span>
            <span>{data.scode}</span>
          </Space>
        )
      }
    },
    { title: '周期', dataIndex: 'freq', width: 100 },
    { title: '时间', dataIndex: 'datetime', width: 100 },
  ])
  const signalRow = {
    key: paramsUrl.get('featureId'),
    label: paramsUrl.get('featureName'),
    value: paramsUrl.get('featureId')
  }

  const [params, setParams] = useState({
    featureId: signalRow.value || '',
    startTime: defaultTime[0].format('YYYY-MM-DD HH:mm:ss'),
    endTime: defaultTime[1].format('YYYY-MM-DD HH:mm:ss'),
    pageNum: 1,
    pageSize: 20
  })
  const onSeach = (val) => {
    setParams({
      ...params,
      pageNum: 1,
      featureId: val.signalList.value,
      freqName: val.freqName,
      startTime: val.dateTime ? val.dateTime[0].format('YYYY-MM-DD HH:mm:ss') : '',
      endTime: val.dateTime ? val.dateTime[1].format('YYYY-MM-DD HH:mm:ss') : '',
    })
  }
  // 翻页实现
  const pageChange = (page, pageSize) => {
    setSignalData({ list: [], count: 0 })
    setParams({
      ...params,
      pageSize: pageSize,
      pageNum: page
    })
  }
  const [firstLoad, setFirstLoad] = useState(false)
  useEffect(() => {
    const getfeatchList = async () => {
      const res = await fetchUserList()
      console.log('品种列表', res)
      await getFreq()
      await getFactor()
      const list = res.length ? res : [{ label: '--请选择--', value: '' }]
      setDefaultopt(list)
      setFirstLoad(true)
    }
    const getFreq = async () => {
      const res = await http.post('/alarm/deliversign/getAllFreq')
      const list = res.body ? res.body.map(item => ({
        label: item.freqName,
        freqKey: item.freqKey,
        value: item.freqName,
        sorter: true
      })) : [{ label: '暂无', value: '' }]
      setFreqListOpt(list)
      console.log('周期列表-', list)
    }
    const getFactor = async () => {
      const res = await http.post('/alarm/deliversign/getAllFactor')
      console.log('因子列表-', res.body)
      const list = res.body ? res.body.map(item => ({
        title: item.factorName,
        key: item.id,
        value: item.id,
        dataIndex: item.factorParam,
        factorParam: item.factorParam,
        label: item.factorName,
        render: (data) => {
          return <>
            {data === undefined ? '-' : data}
          </>
        }
      })) : []
      factorListOptRef.current = list
    }
    const getList = async () => {
      const res = await http.post('/alarm/deliversign/signalsDetail', params)
      const list = res.body.list.map((e, i) => {
        const children = JSON.parse(e.data).map((item, index) => {
          return {
            ...item,
            id: `${i}_${index}`,
            key: `${i}_${index}`,
            featureName: e.featureName,
            scode: e.scode
          }
        })
        return {
          ...e,
          freq: e.freqList,
          children: children.filter(citem => {
            // 过滤全是因子全是0的周期
            let unZero = false
            for (let i = 0; i < factorListOptRef.current.length; i++) {
              const element = factorListOptRef.current[i]
              if (citem[element.dataIndex] !== undefined && citem[element.dataIndex] !== 0) {
                unZero = true
              }
            }
            return unZero
          })
        }
      })

      const nameArr = list.map(e => `${e.featureName} ${e.scode}`)
      const nameWidth = getMaxLength(nameArr) + 70
      if (list.length) {
        const obj = list[0].children[0]
        let keyArr = []
        for (const key in obj) {
          keyArr.push(key)
        }
        const factorList = factorListOptRef.current.filter(e => {
          return keyArr.indexOf(e.factorParam !== -1)
        })
        const col = [
          {
            title: '品种名称',
            width: nameWidth,
            render: (data) => {
              return (
                <Space size="middle">
                  <span>{data.featureName}</span>
                  <span>{data.scode}</span>
                </Space>
              )
            }
          },
          {
            title: '周期', dataIndex: 'freq', width: 100,
            render: (data) => {
              return <>{data === '' ? '-' : data}</>
            }
          },
          { title: '时间', dataIndex: 'datetime', width: 150 },
          ...factorList
        ]
        setColumns(col)
      }
      console.log('预警信号列表111-', list)
      setSignalData({
        list: list,
        count: res.body.total
      })
    }
    if (!firstLoad) {
      getfeatchList()
    }
    if (firstLoad) {
      getList()
    }
  }, [firstLoad, params])
  return (
    <>
      <Card
        title={`预警信号`}
      >
        <Form
          form={form}
          onFinish={onSeach}
          initialValues={{
            signalList: signalRow,
            exchangeId: [],
            dateTime: defaultTime
          }}
        >
          <Form.Item label="品种名称" name="signalList" style={{ display: 'inline-block', width: 300 }}>
            {defaultopt.length ? <DebounceSelect
              showSearch
              placeholder="请选择品种名称"
              fetchOptions={fetchUserList}
              allowClear
              defaultopt={defaultopt}
              style={{ width: 200 }}
              onChange={form.submit}
            /> : <Input
              allowClear
              placeholder='请输入品种名称'
              style={{ width: 200 }}
            />}
          </Form.Item>
          <Form.Item label="周期名称" name="freqName" style={{ display: 'inline-block', width: 300 }}>
            <Select
              allowClear
              placeholder='请选择周期'
              style={{ width: 200 }}
              options={freqListOpt}
              onChange={form.submit}
            ></Select>
          </Form.Item>
          <Form.Item label="时间范围" name="dateTime" style={{ display: 'inline-block', width: 450 }}>
            <RangePicker
              format="YYYY-MM-DD HH:mm"
              showTime={{ format: 'HH:mm', }}
              onChange={form.submit}
            />
          </Form.Item>
          <Form.Item style={{ display: 'inline-block', width: 300, marginBottom: 10 }}>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
          </Form.Item>
        </Form>
        {/* expandedRowKeys={expandedRowKeys} */}
        {/* expandIcon={expandIconOnChange} */}
        <Table
          dataSource={signalData.list}
          rowKey="id"
          key={signalData.list}
          columns={columns}
          defaultExpandAllRows
          size='middle'
          pagination={
            {
              size: 'default',
              showQuickJumper: true,
              showSizeChanger: true,
              pageSize: params.pageSize,
              total: signalData.count,
              current: params.pageNum,
              onChange: pageChange,
              showTotal: (total, range) => `共 ${total} 条`,
            }
          }
          bordered
        ></Table>
      </Card>
    </>

  )
}
export default Signal